package com.example.lp.lpdesignpatterns.thread;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试公平锁在快速且多的发射环境下的时候
 */
public class TestLock2 {

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock(false);
        TestThread testThread = new TestThread();
        AtomicInteger count= new AtomicInteger();
        TestThread.ICallBack callBack = (type) -> {
            try {
                lock.lock();
                count.getAndIncrement();
                System.out.println("----收到消息----" + type);
                Thread.sleep(2000);
                System.out.println("----处理消息耗时4s完成----" + type + "----计数----" + count);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        };
        testThread.startSendFastMessage("-----线程----1----", 1, callBack);
        testThread.startSendFastMessage("-----线程----2----", 3, callBack);
    }

    private static class TestThread {
        interface ICallBack {
            void nowCount(String type);
        }

        public void startSendFastMessage(final String type, final int interVaTime, ICallBack callBack) {
            new Thread(() -> {
                while (true) {
                    try {
                        System.out.println("当前" + type + "消息开始发送");
                         callBack.nowCount(type);
                        Thread.sleep(interVaTime * 100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            }).start();
        }
    }
}
